package com.project.sianet.data;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.util.Log;

import com.project.sianet.entidades.*;

public class MenuParser {

	private static final String tag = "MenuParser";
    
    private DocumentBuilderFactory factory;
    private DocumentBuilder builder;
    private final List<Menu> list;
 
    public MenuParser() {
        this.list = new ArrayList<Menu>();
    }
 
    private String getNodeValue(NamedNodeMap map, String key) {
        String nodeValue = null;
        Node node = map.getNamedItem(key);
        if (node != null) {
            nodeValue = node.getNodeValue();
        }
        return nodeValue;
    }
 
    public List<Menu> getList() {
        return this.list;
    }
 
    /**
     * Parse el file XML con el cuerpo /opcion
     * 
     * @param inStream
     */
    public void parse(InputStream inStream) {
        try {

            this.factory = DocumentBuilderFactory.newInstance();
            this.builder = this.factory.newDocumentBuilder();
            this.builder.isValidating();
            Document doc = this.builder.parse(inStream, null);
 
            doc.getDocumentElement().normalize();
 
            NodeList menuList = doc.getElementsByTagName("opcion");
            final int length = menuList.getLength();
 
            for (int i = 0; i < length; i++) {
                final NamedNodeMap attr = menuList.item(i).getAttributes();
                final String menuNombre = getNodeValue(attr, "name");
                final String menuSrc = getNodeValue(attr, "src");
                int menuOrden = 0;
                String orden = getNodeValue(attr, "order");
                if (orden != null)
                	menuOrden = Integer.parseInt(orden);
 
                // Constructor del objeto Menu
                Menu menu = new Menu(menuNombre, menuSrc, menuOrden, menuSrc);
                 
                // Agrego a la lista
                this.list.add(menu);
                 
                Log.d(tag, menu.toString());
            }
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
    }
	
}
